#include <Windows.h>
#include <stdio.h>
#include <ctime>

// 设置账户线程的数量
const int threads_num = 2;
HANDLE Threads[threads_num];

const int MAX_LOOPNUM = 1e6; //进程最大执行次数
const int MAX_Amount = 1e3;  //每次转出的最大额度
int nAccount1 = 0, nAccount2 = 0;

void WINAPI Account(void *param)
{
    printf("线程 %u 开始运行\n", GetCurrentThreadId());
    srand((unsigned)time(NULL));
    int nLoop = 0;
    int nTemp1, nTemp2, nrand;
    do
    {
        nrand = rand() % MAX_Amount;
        nTemp1 = nAccount1;
        nTemp2 = nAccount2;
        nAccount1 = nTemp1 + nrand;
        nAccount2 = nTemp2 - nrand;
        nLoop++;
    } while ((nAccount1 + nAccount2) == 0);
    printf("余额不对，线程 %u 的第 %d 次转账结束了！\n", GetCurrentThreadId(), nLoop);
}

void creatThreads()
{
    DWORD dwThreadID = 0;
    for (int i = 0; i < threads_num; i++)
    {
        if ((Threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Account, NULL, 0, &dwThreadID)) == NULL)
        {
            printf("线程创建失败！\n");
            exit(0);
        }
        else
        {
            printf("线程 %u 创建成功\n", dwThreadID);
        }
    }
}

int main()
{
    //17271113-创建进程
    printf("17271113:这里没加任何互斥锁和信号量!\n");
    creatThreads();
    WaitForMultipleObjects(threads_num, Threads, TRUE, INFINITE);
    return 0;
}
